<template>
<div>
  <div class="center1">
    <a-button :type="type">+新增楼层</a-button>
    <a-button :type="type" :disabled="deleteIds" @click="editHole">+编辑节点</a-button>
    <a-button :type="type" :disabled="deleteIds" @click="deleteHole">删除节点</a-button>
    <a-button type="primary" @click="openModel" :disabled="keep">保存绘图</a-button>
  </div>
  <From ref="fom" :title="title"></From>
  <div class="center">
    <div style="width:200px">
      <a-directory-tree multiple default-expand-all @select="onSelect">
        <a-tree-node key="000" title="项目1">
          <template v-for="item in tree">
            <a-tree-node :key="item.floor" :title="item.title">
              <template v-for="items in item.children">
                <a-tree-node :key="items._id" :title="items.title" is-leaf />
              </template>
            </a-tree-node>
          </template>
        </a-tree-node>
      </a-directory-tree>
    </div>
    <div id="maps" class="map">
      <div id="popup" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer"></a>
        <div id="popup-content" class="popup-content"></div>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import {
  GeoJSON
} from "ol/format";
import Draw from "ol/interaction/Draw";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import {
  Map,
  View
} from "ol";
import "ol/ol.css";
import MultiPoint from "ol/geom/MultiPoint";
import {
  Circle as CircleStyle,
  Fill,
  Stroke,
  Style
} from "ol/style";
// 投影
import {
  map,
  hole
} from "@/api/article.js";
import From from "./form.vue";
export default {
  components: {
    From,
  },
  data() {
    return {
      map: null,
      visible: false,
      type: "dashed",
      value: "Polygon",
      // JSONd图层
      vector: null,
      draw: null,
      // 围栏图层数据
      weilan: [],
      // 围栏层
      weilanLayer: null,
      json: null,
      // tree
      tree: null,
      // floor
      floor: null,
      // 新增节点按钮
      keep: true,
      // 所有的图层数据
      holeData: [],
      // 当前的图层数据
      editData: {},
      // 删除节点
      deleteId: "",
      title: "新增图层",
    };
  },
  computed: {
    deleteIds() {
      return this.deleteId.length > 5 ? false : true;
    },
  },
  watch: {
    source: {
      deep: true,
      immediate: true,
      handler(a) {
        // console.log(a.getGeometry());
      },
    },
  },
  created() {
    this.getData();
  },
  mounted() {
    this.init();
    this.addInteraction();
  },
  methods: {
    // 初始化地图
    init() {
      this.map = new Map({
        view: new View({
          center: [0, 0],
          zoom: 10,
          // 最大放大倍数
          maxZoom: 14,
          // 最小缩放倍数
          minZoom: 10,
        }),
        // 图层 layers 配置图层的数据源
        layers: null,
        target: "maps",
      });
    },
    // 选择地图
    onSelect(keys) {
      this.deleteId = keys[0];
      // console.log(event);
      console.log(this.deleteId);
      // 判断是不是层
      if (keys[0].toString().length == 1) {
        const json = this.tree.filter((item) => {
          if (item.floor == keys[0]) {
            this.floor = item;
            return true;
          }
        });
        // 删除围栏
        this.deleteWei();
        // 渲染底图
        this.addJSON(json[0].data);
        // 加载其他图层
        this.weilan = [];
        if (json[0].children.length > 0) {
          json[0].children.map((val) => {
            this.weilan.push(JSON.parse(val.data));
          });
          this.setJSON();
        }
      } else {
        // 删除围栏
        this.deleteWei();
        if (keys[0] !== "000") {
          let data = this.holeData.filter((item) => {
            return this.deleteId == item._id;
          });
          console.log(data);
          this.weilan = [];
          this.editData = data[0];
          this.weilan.push(JSON.parse(data[0].data));
          this.setJSON();
        }
      }
    },
    onExpand() {},
    holeChange(e) {
      console.log(e);
    },
    // 获取数据
    async getData() {
      const data = await map("/map/floor");
      this.tree = data;
      // 获取所有子元素
      let arr = [];
      data.map((item) => {
        if (item.children) {
          item.children.map((items) => {
            arr.push(items);
          });
        }
      });
      this.holeData = arr;
    },
    // 删除绘画图层
    deleteHole() {
      hole({}, `/map/hole/${this.deleteId}`, "delete").then(() => {
        this.$message.success("删除成功");
        this.updateDraw();
      });
    },
    // 编辑节点
    editHole() {
      this.$refs.fom.visible = true;
      this.title = "编辑节点";
      this.$refs.fom.listData = this.editData;
    },
    // 打开对话框
    openModel() {
      this.$refs.fom.visible = true;
      this.title = "新增图层";
    },
    // 跟新图层
    updateDraw() {
      this.getData();
      this.keep = true;
      this.onSelect([this.deleteId]);
    },
    // 渲染楼层底图
    async addJSON(json) {
      let source = new VectorSource({
        features: new GeoJSON().readFeatures(json),
      });

      let styles = new Style({
        stroke: new Stroke({
          width: 1,
          color: "pink",
        }),
        fill: new Fill({
          color: "#ccc",
        }),
      });
      this.deleteDitu();
      // 绘画图层
      this.vector = new VectorLayer({
        source: source,
        minZoom: 1,
        // projection: "EPSG:4326", //projection 设置地图的投影坐标系统  默认是EPSG:3857
        renderBuffer: 200,
        zIndex: 1,
        style: styles,
      });
      this.map.addLayer(this.vector);
    },

    // 停止绘画
    stop() {
      this.map.removeInteraction(this.draw);
      this.value = false;
      this.draw = null;
      this.addInteraction();
    },
    start() {
      this.value = "Polygon";
      this.addInteraction();
    },
    // 增加绘制图形
    addInteraction() {
      let styles = new Style({
        stroke: new Stroke({
          width: 3,
          color: "rgba(0,255,255,1)",
        }),
        fill: new Fill({
          color: "rgba(0,255,255,0.1)",
        }),
      });
      if (this.value) {
        this.draw = new Draw({
          source: this.source,
          type: this.value,
          style: styles,
        });
        // 将互动层添加到地图
        this.map.addInteraction(this.draw);
        let _this = this;
        this.draw.on("drawend", function (e) {
          // 获取互动坐标
          const geometry = e.feature.getGeometry();
          let arr = geometry.getCoordinates();
          let geo = {
            type: "Feature",
            properties: {
              name: "围栏二",
            },
            geometry: {
              type: "Polygon",
              coordinates: arr,
            },
          };
          console.log(JSON.stringify(geo));
          _this.$refs.fom.listData.data = JSON.stringify(geo);
          _this.$refs.fom.listData.floor_id = _this.floor._id;
          _this.$refs.fom.listData.floor = _this.floor.floor;
          _this.weilan.push(geo);
          _this.keep = false;
        });
      }
    },
    // 自定义图形
    setJSON() {
      let styles = [
        new Style({
          stroke: new Stroke({
            color: "blue",
            width: 1,
          }),
          fill: new Fill({
            color: "rgba(0, 0, 255, 0.1)",
          }),
        }),
        new Style({
          geometry: function (feature) {
            const coordinates = feature.getGeometry().getCoordinates()[0];
            return new MultiPoint(coordinates);
          },
        }),
      ];
      let geojsonObject = {
        type: "FeatureCollection",
        crs: {
          type: "name",
          properties: {
            name: "EPSG:3857",
          },
        },
        features: this.weilan,
      };
      let a = new GeoJSON().readFeatures(geojsonObject);

      let source = new VectorSource({
        features: a,
      });

      this.weilanLayer = new VectorLayer({
        source: source,
        style: styles,
        zIndex: 30,
      });
      this.map.addLayer(this.weilanLayer);
    },
    // 取消围栏
    deleteWei() {
      this.map.removeLayer(this.weilanLayer);
    },
    //增加绘画图层addFeature
    test() {
      this.map.removeLayer(this.weilanLayer);
      this.setJSON();
      // this.weilanLayer.source = [];
    },
    deleteDitu() {
      this.map.removeLayer(this.vector);
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  margin-left: 200px;
  width: 100%;
  height: 800px;
}

.ol-popup {
  position: absolute;
  background-color: #ccc;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  // padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.popup-content {
  width: 400px;
}

.ol-popup-closer:after {
  content: "✖";
}

#marker {
  width: 20px;
  height: 20px;
  background: red;
  border-radius: 50%;
}

#textInfo {
  width: 200px;
  height: 40px;
  line-height: 40px;
  background: burlywood;
  color: yellow;
  text-align: center;
  font-size: 20px;
}
</style>
